﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using FractalistWX.Dal;
using FractalistWX.Tool;

namespace FractalistWX
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var cookie = new HttpCookie("token", "");
                cookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(cookie);

                if (!string.IsNullOrEmpty(Tool.Tools.CheckVar(Request["ReturnUrl"], "")))
                {
                    Response.Redirect("login.aspx");
                    Response.End();
                }
                if (Tools.SafeSql(Request.QueryString["op"], 0) != null && Tools.SafeSql(Request.QueryString["op"], 0) == "logout")
                {
                    FormsAuthentication.SignOut();
                    return;
                }
            }
        
        }

        private bool authenticated(string userName, string password, out int roles_Id, out string errorInfo, out string src)
        {
            src = SQLTool.GetFirstField("select Role from wechat_manage where username='" + Tool.Tools.SafeSql(userName,0) + "' and password='" + Tool.Tools.SafeSql(Tool.Tools.MD5(password),0) + "' limit 1");
            if (!string.IsNullOrEmpty(src))
            {
                roles_Id = 1;
                errorInfo = "";
                return true;
            }
            else
            {
                roles_Id = 1;
                errorInfo = "用户名密码有误!";
                return false;
            }
        }

        private string getRoles(int roles_Id)
        {
            //return userCtrl.GetUserRoleName(roles_Id);
            return "超级管理员";
        }

        protected void BTN_Login_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Tool.Tools.CheckVar(Request["ReturnUrl"], "")))
            {
                Response.Redirect("login.aspx");
                Response.End();
            }
            bool isPersistent = this.CheckBox1.Checked;
            string userName =Tools.SafeSql(this.TextBox_UserName.Text.Trim(),0);
            string password = Tools.SafeSql(this.TextBox_Password.Text.Trim(),0);
            string userData = "";
            string errorInfo = "";
            string src = "";
            int roles_Id;
            if (string.IsNullOrEmpty(userName))
            {
                L1.Text = "请输入管理员";
                //Global.log.Warn("登录失败，验证码不正确。 " + validateCode.Text + " | " + Request.UserHostAddress + " | " + Request.UserAgent);
                return;
            }
            if (string.IsNullOrEmpty(password))
            {
                L1.Text = "请输入登录密码";
                //Global.log.Warn("登录失败，验证码不正确。 " + validateCode.Text + " | " + Request.UserHostAddress + " | " + Request.UserAgent);
                return;
            }
            if (MySession.ValidateCode == null || validateCode.Text != MySession.ValidateCode)
            {
                L1.Text = "验证码不正确";
                //Global.log.Warn("登录失败，验证码不正确。 " + validateCode.Text + " | " + Request.UserHostAddress + " | " + Request.UserAgent);
                return;
            }

            var uids = System.Configuration.ConfigurationManager.AppSettings["userName"].Split('|');
            var  pwds = System.Configuration.ConfigurationManager.AppSettings["passWord"].Split('|');
            for (var i = 0; i < uids.Length; i++)
            {
                if (uids[i] == userName && pwds[i] == password)
                {
                    var token = userName + "|" + password;
                    var encryptToken = StrUtil.EncriptDES(token);

                    var cookie = new HttpCookie("token", Server.UrlEncode(encryptToken));

                    Session["token"] = token;
                    Response.Cookies.Add(cookie);

                    Response.Redirect("~/Manage/index.aspx");
                    break;
                }
            }

            validateCode.Text = "";
            L1.Text = "登录失败";

              

            //if (authenticated(userName, password, out roles_Id, out errorInfo, out src))
            ////if (authenticated(userName, StringHelper.MD5(password).ToLower(), out roles_Id, out errorInfo))
            //{
            //    Session.Remove("validateRndCode");
            //    userData = getRoles(roles_Id);
            //    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            //        1,
            //        userName + "|" + src,
            //        System.DateTime.Now,
            //        System.DateTime.Now.AddMonths(1),
            //        true,
            //        userData,
            //        FormsAuthentication.FormsCookiePath);

            //    // Encrypt the ticket.
            //    string encTicket = FormsAuthentication.Encrypt(ticket);

            //    // Create the cookie.
            //    //Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

            //    // Redirect back to original URL.
            //    FormsAuthentication.SetAuthCookie(userName + "|" + src, isPersistent);
            //    //Global.log.Warn("登录成功。 " + userName + " | " + validateCode.Text + " | " + Request.UserHostAddress + " | " + Request.UserAgent);

            //    if (Tools.SafeSql(Request.QueryString["ReturnUrl"],0) == null || Tools.SafeSql(Request.QueryString["ReturnUrl"],0) == "")
            //    {
            //        Response.Redirect("~/Manage/index.aspx");
            //    }
            //    else
            //    {
            //        Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, true));
            //    }
            //}
            //Global.log.Warn("登录失败。 " + userName + " | " + password + " | " + Request.UserHostAddress + " | " + Request.UserAgent);
          
        }
    }
}